import { ForbiddenException, Injectable } from '@nestjs/common';
import { 
    Create<%= className %>Dto,
    Update<%= className %>Dto,
    Query<%= className %>Dto,
  } from './dto/<%= tableInfo.table_name %>.dto';
import { InjectRepository, InjectEntityManager } from '@nestjs/typeorm';
import { Repository, EntityManager, In} from 'typeorm';
import { <%= className %> } from './entities/<%= tableInfo.table_name %>.entity';
import { ApiTags } from '@nestjs/swagger';
import { Workbook } from 'exceljs';
import { Request, Response } from 'express';
import { User } from '../user/entities/user.entity';

@ApiTags('<%= tableInfo.function_name %>')
@Injectable()
export class <%= className %>Service {
  constructor(
    @InjectRepository(<%= className %>) private readonly <%= tableInfo.table_name %>: Repository<<%= className %>>,
    @InjectEntityManager() private entityManager: EntityManager,
  ) {}

  /**
   * 创建<%= tableInfo.function_name %>
   * @param create<%= className %>Dto
   * @returns
   */
  async create(create<%= className %>Dto: Create<%= className %>Dto, req: Request) {
    let user = req.user as User;
    let params = create<%= className %>Dto.form;
    params.create_by = user.username;
    return this.<%= tableInfo.table_name %>.save(params);
  }

  /**
   * <%= tableInfo.function_name %>列表
   * @param query
   * @returns
   */
  async findAll(query: Query<%= className %>Dto) {
    let queryBuilder = this.<%= tableInfo.table_name %>.createQueryBuilder('<%= tableInfo.table_name %>');
    // 处理查询条件
    <%_ for (let i = 0; i < query.length; i++) { -%>
    <%# 查询条件类型不为between -%>
    <%_ if(query[i].query_type != 'BETWEEN') {-%>    
    if (query.<%= query[i].column_name %>) {
      queryBuilder = queryBuilder.andWhere('<%= tableInfo.table_name %>.<%= query[i].column_name %> <%= query[i].query_type_map %> :key', {
        key: `<%= query[i].query_type == 'LIKE' ? '%' : ''_%>${query.<%= query[i].column_name %>}<%= query[i].query_type == 'LIKE' ? '%' : ''_%>`,
      });
    }
    <%_ } else { -%>
    <%# 查询条件类型为between -%>
    queryBuilder = queryBuilder.andWhere(
      '<%= tableInfo.table_name %>.<%= query[i].column_name %> BETWEEN :beginTime AND :endTime',
      {
        beginTime: query.begin_<%= query[i].column_name %>,
        endTime: query.end_<%= query[i].column_name %>,
      },
    );
    <%_ } -%>
    <%_ } -%>

    // 处理分页
    if (!query.pageNum || query.pageNum < 1) {
      query.pageNum = 1;
    }
    if (!query.pageSize || query.pageSize < 1) {
      query.pageSize = 10;
    }
    queryBuilder = queryBuilder
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize)
    let total = await queryBuilder.getCount();
    let list = await queryBuilder.getMany();
    return {
      pageNum: query.pageNum,
      pageSize: query.pageSize,
      total,
      list,
    };
  }

  /**
   * <%= tableInfo.function_name %>详情
   * @param id
   * @returns
   */
  async findOne(id: number) {
    let data = await this.<%= tableInfo.table_name %>.findOne({
      where: {
        <%= primaryKey %>: id,
      },
    });
    return {
      data
    };
  }

  /**
   * 修改<%= tableInfo.function_name %>
   * @param id
   * @param update<%= className %>Dto
   * @param req
   * @returns
   */
  async update(id: number, update<%= className %>Dto: Update<%= className %>Dto,req:Request) {
    let params = update<%= className %>Dto.form;
    let user = req.user as User;
    params.update_by = user.username
    return this.<%= tableInfo.table_name %>.update(<%= primaryKey %>, params);
  }

  /**
   * 删除<%= tableInfo.function_name %>
   * @param ids
   * @returns
   */
  async remove(ids: number[]) {
    try {
      await this.entityManager.transaction(async (manager) => {
        await manager.delete(<%= className %>, { <%= primaryKey %>: In(ids) });
      });
    } catch (err) {
      return err;
    }
  }

  /**
   * 导出为表格
   * @param res
   */
  async exportToExcel(res: Response) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('<%= tableInfo.function_name %>');

    worksheet.columns = [
    <%_ for(let i = 0; i < column.length; i++) { -%>
      { header: '<%= column[i].column_comment || column[i].column_name %>', key: '<%= column[i].column_name %>', width: 10 },
    <%_ } -%>
    ];

    const data = await this.<%= tableInfo.table_name %>.find();
    worksheet.addRows(data);
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    let filename = encodeURIComponent('<%= tableInfo.function_name %>.xlsx')  // 这里中文需要转码
    res.setHeader('Content-Disposition', 'attachment; filename='+filename+'');
    res.setHeader('Cache-Control', 'max-age=0');
    const file = await workbook.xlsx.writeBuffer();
    res.end(file)
  }
}
